<template>
  <el-dialog custom-class="label-dialog-box" v-model="dialogVisible" title="批量标签" width="700px" :before-close="cancelHandel">
    <section class="dialog-content-box">
      <div class="title-box">
        <el-radio-group v-model="dialogData.labelType">
          <span v-if="dialogData.labelChooseType == 1">
            <el-radio :label="3">批量打标签</el-radio>
            <el-tooltip content="若内容本身已有所选标签，则不针对此内容重复打标签">
              <img class="help_icon" src="@/assets/image/customer/help_icon.png" alt="" />
            </el-tooltip>
            <el-radio :label="4">批量移除标签</el-radio>
            <el-tooltip content="若内容本身没有有所选标签，则不针对此内容重复移除标签">
              <img class="help_icon" src="@/assets/image/customer/help_icon.png" alt="" />
            </el-tooltip>
          </span>
          <span v-else>
            <el-radio :label="1">满足任意一个标签</el-radio>
            <el-radio :label="2">同时满足所有标签</el-radio>
            <el-radio :label="0">无标签</el-radio>
          </span>
        </el-radio-group>
        <div class="right">
          <div class="refresh" @click="getListTagFun(true)"
            ><el-icon class="icon"><refresh-right /></el-icon><span>刷新数据</span></div
          >
          <span>标签不存在？</span>
          <span @click="toCreate" class="active">
            <span class="fa fa-edit link-btn" @click="toCreatedLink">去创建</span>
          </span>
        </div>
      </div>
      <div class="seach">
        <el-input v-model="dialogData.seachKey" placeholder="搜索标签组、标签" :prefix-icon="Search" @input="seachTab" />
      </div>
      <el-tabs v-model="dialogData.activeName" type="card" class="label-tabs-box" @tab-change="handleClick" v-if="dialogData.labelType != 5">
        <el-tab-pane class="label-list-content" :label="item.name" :name="item.id" v-for="item in labelList" :key="item.id">
          <el-scrollbar max-height="400px" @scroll="pageScroll">
            <div class="label-list" v-for="itm in item.list" :key="itm.group_id" :id="'tab-item-' + item.id">
              <div class="title">{{ itm.group_name }}</div>
              <div class="label-item-box">
                <div @click="chooseTag(it)" :class="it.check ? 'active' : ''" v-for="(it, ind) in itm.tags" :key="ind">{{ it.name }}</div>
              </div>
            </div>
          </el-scrollbar>
        </el-tab-pane>
      </el-tabs>
    </section>

    <template #footer>
      <div class="dialog-footer">
        <div class="footer_desc">
          已选<span>{{ chooseDataArr.length }}</span
          >个标签，将为客户<span class="typeName">{{ labelTypeNameArr[dialogData.labelType] }}</span>
        </div>
        <div>
          <el-button plain @click="clearChoose">清空</el-button>
          <el-button @click="cancelHandel">取消</el-button>
          <el-button type="primary" @click="submitHandel">保存</el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
  import { nextTick, reactive, ref, watch, onMounted } from 'vue'
  import { Search } from '@element-plus/icons-vue'
  import { listGroupType, listTag } from '@/api/customerCenter'
  const emit = defineEmits(['save'])
  const dialogVisible = ref(false)
  const dialogData = ref({})
  const labelList = ref([])
  const chooseDataArr = ref([]) //当前选中的标签
  const labelTypeNameArr = ref(['无标签', '满足任意一个标签', '同时满足所有标签', '批量打标签', '批量移除标签'])
  let nowPageHeight = 0
  let pageParam = { page: 1, page_size: 50 }
  let canScroll = true
  let isCreate = false //当前是否前往创建标签页面了

  const initDataFun = (type: number) => {
    dialogData.value = {
      labelChooseType: type == 2 ? 2 : 1, // 1是批量打标签   2 是选择标签
      labelType: type == 2 ? 1 : 3, //3批量打标签  4删除  1 满足任意一个标签  2 同时满足所有标签  0无标签
      labelTypeName: '',
      seachKey: '',
      activeName: 1 //当前标签页
    }
  }

  // 获取标签组类别列表
  const getListGroupType = () => {
    return new Promise((res, ref) => {
      listGroupType({})
        .then((r: any) => {
          res(r)
        })
        .catch((e: any) => {
          ref(e)
        })
    })
  }

  watch(dialogVisible, async (val) => {
    if (val) {
      isCreate = false //初始化
      nowPageHeight = 0
      pageParam = {
        page: 1,
        page_size: 50
      }
      initDataFun(dialogData.value.labelChooseType)
      let groupData = await getListGroupType()
      labelList.value = groupData && groupData.length > 0 ? groupData : []
      dialogData.value.activeName = labelList.value.length > 0 ? labelList.value[0].id : ''
      getListTagFun()
    }
  })

  // 获取标签组内的数据
  const getListTagFun: any = (isSeach) => {
    let index = labelList.value.findIndex((it) => {
      return it.id == dialogData.value.activeName
    })
    if (!labelList.value[index].list) {
      if (labelList.value[index]) labelList.value[index].list = []
    }
    if (labelList.value[index].list && labelList.value[index].list.length > 0 && !isSeach) {
      return
    }
    if (!dialogData.value.activeName) {
      return
    }
    listTag({
      keyword: dialogData.value.seachKey,
      type_list: dialogData.value.activeName,
      page: pageParam.page,
      page_size: pageParam.page_size
    })
      .then((r: any) => {
        r.data.forEach((item: any) => {
          item.tags.forEach((itm: any) => {
            let indx = chooseDataArr.value.findIndex((it) => {
              return it.id == itm.id
            })
            if (indx > -1) {
              itm.check = true
            }
          })
        })
        labelList.value[index].list = r.data
        nextTick(() => {
          canScroll = true
          nowPageHeight = document.querySelector('#tab-item-' + dialogData.value.activeName)?.offsetHeight || 0
        })
      })
      .catch((e: any) => {
        canScroll = true
      })
  }

  onMounted(() => {
    document.addEventListener('visibilitychange', function () {
      //浏览器切换事件
      if (document.visibilityState != 'hidden' && isCreate) {
        getListTagFun()
        isCreate = false
      }
    })
  })

  const cancelHandel = () => {
    clearChoose()
    dialogVisible.value = false
  }
  // 前往创建
  const toCreate = () => {
    isCreate = true
  }

  // 滚动加载
  const pageScroll = (e: any) => {
    if (nowPageHeight - 244 <= e.scrollTop && canScroll) {
      canScroll = false
      pageParam.page = pageParam.page + 1
      getListTagFun()
    }
  }

  // 保存数据
  const submitHandel = () => {
    let { labelChooseType, labelType } = dialogData.value
    let idList = chooseDataArr.value.map((it) => {
      return it.id
    })
    if (dialogData.value.labelType != 5) {
      emit('save', { labelChooseType, labelType, data: chooseDataArr.value, idList })
    } else {
      emit('save', { labelChooseType, labelType, data: [], idList: [] })
    }
    dialogVisible.value = false
  }

  // 选择选项卡
  const handleClick = () => {
    pageParam = {
      page: 1,
      page_size: 50
    }
    getListTagFun()
  }

  // 选择标签
  const chooseTag = (val: object) => {
    val.check = !val.check
    let index = chooseDataArr.value.findIndex((it) => {
      return it.id == val.id
    })
    if (index > -1) {
      chooseDataArr.value.splice(index, 1)
    } else {
      chooseDataArr.value.push(val)
    }
  }
  // 清空选中的标签
  const clearChoose = () => {
    chooseDataArr.value = []
    let keyArr = Object.keys(labelList.value)
    keyArr.forEach((item: string) => {
      if (labelList.value[item].list) {
        labelList.value[item].list.forEach((itm: object) => {
          if (itm.tags && itm.tags.length > 0) {
            itm.tags.forEach((it: object) => {
              it.check = false
            })
          }
        })
      }
    })
  }

  let time = ''
  const seachTab = (val: string) => {
    if (time) {
      clearTimeout(time)
    }
    time = setTimeout(() => {
      pageParam = { page: 1, page_size: 50 }
      getListTagFun(true)
    }, 500)
  }

  const toCreatedLink = () => {
    window.open('/customer/tag/manage', '_blank')
  }
  
  defineExpose({
    dialogVisible,
    dialogData,
    chooseDataArr //回显的标签数据  {id:***,name:***}
  })
</script>

<style lang="scss" scoped>
  .dialog-content-box {
    border-top: solid 1px #eaeaea;
    border-bottom: solid 1px #eaeaea;
    padding: 20px 30px;
    .title-box {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      .help_icon {
        cursor: pointer;
        width: 14px;
        height: 14px;
        position: relative;
        left: -24px;
      }
      .right {
        font-size: 14px;
        font-family: STHeitiSC-Light, STHeitiSC;
        color: #969696;
        span {
          vertical-align: middle;
        }
        .active {
          color: #ff6b00;
          cursor: pointer;
          a {
            color: #ff6b00;
            text-decoration: none;
          }
        }
        .refresh {
          cursor: pointer;
          display: inline-block;
          line-height: 19px;
          margin-right: 10px;
          .icon {
            vertical-align: middle;
            font-size: 16px;
            margin: 0 6px;
          }
        }
        .refresh:hover {
          color: #0081ff;
          .icon {
            color: #0081ff;
          }
        }
      }
    }
    .seach {
      margin-bottom: 20px;
    }
    .label-list-content {
      border: solid 1px #eaeaea;
      height: 300px;
      box-sizing: border-box;
      overflow-y: scroll;
      padding: 20px 13px;
      .label-list {
        margin-bottom: 14px;
        .title {
          font-size: 14px;
          font-family: STHeitiSC-Light, STHeitiSC;
          color: #33302d;
          margin-bottom: 10px;
        }
        .label-item-box {
          div {
            display: inline-block;
            vertical-align: middle;
            margin-right: 16px;
            background: #ffffff;
            border: 1px solid #eaeaea;
            height: 22px;
            line-height: 22px;
            padding: 0 10px;
            font-size: 14px;
            font-family: STHeitiSC-Light, STHeitiSC;
            color: #969696;
            cursor: pointer;
            margin-bottom: 10px;
            &.active {
              border: 1px solid #ff6b00;
              color: #ff6b00;
            }
          }
        }
      }
    }
    .label-list-content::-webkit-scrollbar {
      display: none;
    }
  }
  .dialog-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .footer_desc {
      font-size: 14px;
      font-family: STHeitiSC-Light, STHeitiSC;
      color: #33302d;
      span {
        margin: 0 5px;
        color: #ff6b00;
      }
      .typeName {
        color: #3e82f9;
      }
    }
  }
</style>

<style lang="scss">
  .label-tabs-box .el-tabs__header {
    margin-bottom: 0;
  }
  .label-tabs-box .el-tabs__item {
    background: #f9f9f9;
    color: #969696;
  }
  .label-tabs-box .is-active {
    background: white;
    color: #ff6b00;
  }
</style>
